import { SearchResult, Suggest } from '@/types/data'
import { SearchAction } from '@/types/store'
import { getHistory } from '@/utils/storage'
type SearchType = {
  suggestList: Suggest
  histories: string[]
  searchResult: SearchResult
}
const initValue: SearchType = {
  suggestList: [],
  histories: getHistory(),
  searchResult: {} as SearchResult,
}

export default function search(
  state = initValue,
  action: SearchAction
): SearchType {
  if (action.type === 'search/getSuggestionList') {
    return { ...state, suggestList: action.payload }
  }
  if (action.type === 'search/clearSuggest') {
    return { ...state, suggestList: [] }
  }
  if (action.type === 'search/history') {
    // const old = state.histories || []
    return {
      ...state,
      histories: action.payload,
    }
  }
  if (action.type === 'search/getSearchDetail') {
    const old = state.searchResult.results || []
    return {
      ...state,
      searchResult: {
        ...state.searchResult,
        results: [...old, ...action.payload.results],
      },
    }
  }
  return state
}
